

/// @file Rx3NavData.hpp
/// Encapsulates RINEX ver 3.02 Navigation data
/// modified from Rinex3NavData, but remove the fftextstream
/// and ffdata class for easy reading and using.
/// by shoujian zhang

#ifndef Rx3NavData_HPP
#define Rx3NavData_HPP

#include <list>
#include <string>

#include "StringUtils.hpp"
#include "CommonTime.hpp"
#include "GloEphemeris.hpp"
#include "GPSEphemeris.hpp"
#include "GalEphemeris.hpp"
#include "BDSEphemeris.hpp"
#include "QZSEphemeris.hpp"
#include "SatID.hpp"
#include "Rx3NavHeader.hpp"

using namespace gpstk;

namespace gnssbox 
{
      /// @ingroup FileHandling
      //@{

      /**
       * This class models a RINEX 3 Nav record.
       *
       */

   class Rx3NavData                       
   {
   public:
         /** Constructor
          * @warning CHECK THE PRNID TO SEE IF THIS DATA IS VALID BEFORE
          *          USING!!!.
          */
      Rx3NavData(void)
            : time(CommonTime::BEGINNING_OF_TIME), 
              PRNID(-1), fitint(4), 
              headerRead(false), headerWrite(false), lineNumber(0)
      {}

         /// Initializes the nav data with a GloEphemeris
      Rx3NavData(const GloEphemeris& gloe);

         /// Initializes the nav data with a GPSEphemeris
      Rx3NavData(const GPSEphemeris& gpseph);

         /// Initializes the nav data with a GalEphemeris
      Rx3NavData(const GalEphemeris& galeph);

         /// Initializes the nav data with a BDSEphemeris
      Rx3NavData(const BDSEphemeris& bdseph);

         /// Initializes the nav data with a QZSEphemeris
      Rx3NavData(const QZSEphemeris& qzseph);

         /// Destructor
      virtual ~Rx3NavData() {}

         /// Rx3NavData is "data" so this function always returns true.
      virtual bool isData(void) const {return true;}

         /// Write selected info (system dependent) as a single line
      std::string dumpString(void) const;

         /// A debug output function.
         /// Prints the PRN id and the IODC for this record.
      virtual void dump(std::ostream& s) const;

         /// Converts Rx3NavData to a GPSEphemeris object.
      operator GPSEphemeris() const throw();

         /// Converts this Rx3NavData to a GloEphemeris object.
      operator GloEphemeris() const throw();

         /// Converts Rx3NavData to a GalEphemeris object.
      operator GalEphemeris() const throw();

         /// Converts Rx3NavData to a BDSEphemeris object.
      operator BDSEphemeris() const throw();

         /// Converts Rx3NavData to a QZSEphemeris object.
      operator QZSEphemeris() const throw();

         /// Converts the (non-CommonTime) data to an easy list
         /// for comparison operators.
      std::list<double> toList() const;

         /// Sort on time, then satellite; for use with Rinex3EphemerisStore
      bool operator<(const Rx3NavData& right) const
      {
         CommonTime t(time),r(right.time);
         t.setTimeSystem(TimeSystem::Any);
         r.setTimeSystem(TimeSystem::Any);
         if(t == r) return (sat < right.sat);
         return (t < r);
      }

      bool headerRead;
      bool headerWrite;

      Rx3NavHeader header;
      int lineNumber;


         /** @name General Data */
         //@{
      CommonTime time;     ///< Time according to the sat/epoch record (TOC)
      std::string satSys;  ///< Satellite system of Epoch: G,R,E,S,C
      short PRNID;         ///< SV PRN ID
      SatID sat;      ///< SatID (from PRNID & satSys)
      long HOWtime;        ///< Time of subframe 1-3 (sec of week)
      short weeknum;       ///< GPS full week corresponding to HOWtime of SF1
                           ///< (N.B.:in RINEX files, week number corresponds
                           /// >to ToE, not GLO)
      double accuracy;     ///< SV accuracy (m)
      short health;        ///< SV health
         //@}

         /** @name GPS Data */
         //@{
      short   codeflgs;    ///< L2 codes
      short   L2Pdata;     ///< L2 P data flag
      double  IODC;        ///< Index of data-clock
      double  IODE;        ///< Index of data-eph
         //@}

         /** @name GLO Data */
         //@{
      double  TauN;        ///< SV clock bias (sec)
      double  GammaN;      ///< SV relative frequency bias
      double  MFTraw;      ///< Message frame time (sec of UTC week) <double>
      long    MFtime;      ///< Message frame time (sec of UTC week) <long>
      short   freqNum;     ///< Frequency number (-7..+12)
      double  ageOfInfo;   ///< Age of oper. information (days)
         //@}

         /** @name GAL Data */
         //@{
      short   datasources; ///< Data sources
      double  IODnav;      ///< Index of data-eph
         //@}

         /** @name GEO Data */
         //@{
      double  accCode;     ///< Accuracy code (URA, meters)
      double  IODN;        ///< Issue of data navigation, DO229,
                           ///< 8 first bits after Message type if MT9
         //@}

         /** @name Clock Information */
         //@{
      double  Toc;         ///< Time of clock (sec of week)
      double  af0;         ///< SV clock error (sec)
      double  af1;         ///< SV clock drift (sec/sec)
      double  af2;         ///< SV clock drift rate (sec/sec**2)
      double  Tgd;         ///< Group delay diff. (sec) (GPS, BDS:B1/B3 GAL:E5a/E1)
      double  Tgd2;        ///< Group delay differential (sec) (BDS:B2/B3 GAL:E5b/E1)
         //@}

         /** @name Harmonic Perturbations */
         //@{
      double  Cuc;         ///< Cosine latitude (rad)
      double  Cus;         ///< Sine latitude (rad)
      double  Crc;         ///< Cosine radius (m)
      double  Crs;         ///< Sine radius (m)
      double  Cic;         ///< Cosine inclination (rad)
      double  Cis;         ///< Sine inclination (rad)
         //@}

         /** @name Major Ephemeris Parameters */
         //@{
      double  Toe;         ///< Ephemeris epoch (sec of week)
      double  M0;          ///< Mean anomaly (rad)
      double  dn;          ///< Correction to mean motion (rad/sec)
      double  ecc;         ///< Eccentricity
      double  Ahalf;       ///< SQRT of semi-major axis (m**1/2)
      double  OMEGA0;      ///< Rt ascension of ascending node (rad)
      double  i0;          ///< Inclination (rad)
      double  w;           ///< Argument of perigee (rad)
      double  OMEGAdot;    ///< Rate of Rt ascension (rad/sec)
      double  idot;        ///< Rate of inclination angle (rad/sec)
      double  fitint;      ///< Fit interval
         //@}

         /** @name Tabular Ephemeris Parameters */
         //@{
      double  px, py, pz;  ///< SV position
      double  vx, vy, vz;  ///< SV velocity
      double  ax, ay, az;  ///< SV acceleration
         //@}

         /** This function retrieves a RINEX 3 NAV record from the given
          *  fstream.
          */
      virtual void reallyGetRecord(std::fstream& strm)
         noexcept(false);


         /// Outputs the record to the fstream \a s.
      virtual void reallyPutRecord(std::fstream& strm) 
         noexcept(false);

   private:

         /** Parses string \a currentLine to obtain PRN id and epoch.
          *  @param strm RINEX Nav stream
          */
      void getPRNEpoch(std::fstream& strm)
         noexcept(false);


         /**  Read and parse the nth record after the epoch record
          *   @param int n record number (1-7), for nth record after
          *     the epoch line
          *   @param Rinex3NavStream strm stream to read from
          */
      void getRecord(const int& n, std::fstream& strm)
         noexcept(false);

         /** Generates the PRN/epoch line and outputs it to strm
          *  @param strm RINEX Nav stream
          */
      void putPRNEpoch(std::fstream& strm) 
         noexcept(false);


         /** Construct and write the nth record after the epoch record
          *  @param int n                 Record number (1-7), for nth record
          *                               after the epoch line.
          *  @param Rinex3NavStream strm  Stream to read from.
          */
      void putRecord(const int& n, std::fstream& strm) 
         noexcept(false);

         /** Helper routine for constructors of this from
          * OrbitEph-based Ephemerides */
      void loadFrom(const OrbitEph *oeptr);

         /// Helper routine for casts from this to OrbitEph-based Ephemerides
      void castTo(OrbitEph *oeptr) const;


   }; // End of class 'Rx3NavData'

       // global re-define the operator >> for reading from file stream
    inline std::fstream& operator>>(std::fstream& strm, Rx3NavData& data)
    {
        try
        {
            data.reallyGetRecord(strm);
            return strm;
        }
        catch(EndOfFile& e)
        {
            GPSTK_RETHROW(e);
        }
    }

    // global re-define the operator << for reading from file stream
    inline std::fstream& operator<<(std::fstream& strm, Rx3NavData& data)
    {
        data.reallyPutRecord(strm);
        return strm;
    }

      //@}

}  // End of namespace gpstk

#endif   // Rx3NavData_HPP
